package com.sl.au.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Account;
import com.sl.au.entity.ContractInfoView;
import com.sl.au.entity.Customer;
import com.sl.au.entity.CustomerPriceView;
import com.sl.au.entity.EXDEcustomerViewTotal;
import com.sl.au.entity.Module;
import com.sl.au.entity.Option;
import com.sl.au.entity.SaleArea;
import com.sl.au.entity.User;
import com.sl.au.service.CustomerService;
import com.sl.au.service.ExdeCustomerPriceViewService;
import com.sl.au.service.ExdeCustomerViewTotalService;
import com.sl.au.service.OptionService;
import com.sl.au.service.SaleAreaService;


@RestController
@RequestMapping(value="/ui/CustomerTotalIndex")
public class CustomerTotalController extends BaseController{
	@Autowired
	ExdeCustomerViewTotalService exdeCustomerViewTotalService;
	
	@Autowired
	OptionService optionService;
	
	@Autowired
	CustomerService customerService;
	
	@Autowired
	SaleAreaService saleAreaService;
	
	@Autowired
	ExdeCustomerPriceViewService exdeCustomerPriceViewService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = this.createLayoutView("CustomerTotal/CustomerTotalIndex");
		System.out.println(request.getParameter("deptName"));
		String[] areaNames = null;
		String[] superiors = null;
		if(StringUtils.hasText(request.getParameter("areaName"))){
			areaNames = request.getParameter("areaName").toString().split(",");//片区
		}
		if(StringUtils.hasText(request.getParameter("deptName"))){
			superiors = request.getParameter("deptName").toString().split(",");//部门
		}
		List<SaleArea> orderAreas = saleAreaService.getRepository().getAllSaleArea();
		List<SaleArea> SaleOrderAreas = new ArrayList<SaleArea>();//销售
		List<SaleArea> CompleteOrderAreas = new ArrayList<SaleArea>();//成套
		List<SaleArea> ForeignOrderAreas = new ArrayList<SaleArea>();//外贸
		for(SaleArea orderArea : orderAreas){
			orderArea.setIsSelected(false);
			if(orderArea.getSuperior().equals("销售处")){
				if(superiors!=null&&superiors.length>0){
					if(areaNames!=null&&areaNames.length>0){
						for(int i=0;i<areaNames.length;i++){
							if(areaNames[i].equals(orderArea.getSuperiorArea()))
								orderArea.setIsSelected(true);
						}
					}else{
						for(int i=0;i<superiors.length;i++){
							if(superiors[i].equals(orderArea.getSuperior()))
								orderArea.setIsSelected(true);
						}
					}
				}
				if(orderArea.getAreaName().equals("销售处-分管领导")){
				}else{
					if(orderArea.getAreaName().equals("科长")){
					}else{
						SaleOrderAreas.add(orderArea);
					}
				}
			}
			if(orderArea.getSuperior().equals("成套处")){
				if(superiors!=null&&superiors.length>0){
					if(areaNames!=null&&areaNames.length>0){
						for(int i=0;i<areaNames.length;i++){
							if(areaNames[i].equals(orderArea.getSuperiorArea()))
								orderArea.setIsSelected(true);
						}
					}else{
						for(int i=0;i<superiors.length;i++){
							if(superiors[i].equals(orderArea.getSuperior()))
								orderArea.setIsSelected(true);
						}
					}
				}
				if(orderArea.getAreaName().equals("其他")){
				}else{
					if(orderArea.getAreaName().equals("成套处分管领导")){
					}else{
						CompleteOrderAreas.add(orderArea);
					}
				}
			}
			if(orderArea.getSuperior().equals("外贸处")){
				if(superiors!=null&&superiors.length>0){
					if(areaNames!=null&&areaNames.length>0){
						for(int i=0;i<areaNames.length;i++){
							if(areaNames[i].equals(orderArea.getSuperiorArea()))
								orderArea.setIsSelected(true);
						}
					}else{
						for(int i=0;i<superiors.length;i++){
							if(superiors[i].equals(orderArea.getSuperior()))
								orderArea.setIsSelected(true);
						}
					}
				}
				if(orderArea.getAreaName().equals("外贸处-分管领导")){
				}else{
					ForeignOrderAreas.add(orderArea);
				}
			}
		}
		modelAndView.addObject("SaleOrderAreas", SaleOrderAreas);
		modelAndView.addObject("CompleteOrderAreas", CompleteOrderAreas);
		modelAndView.addObject("ForeignOrderAreas", ForeignOrderAreas);
		
		//modelAndView.addObject("dutyOfficers", optionService.getRepository().findByGroup(request.getParameter("areaName")));//责任人
		
		modelAndView.addObject("industryInfos", optionService.getRepository().findByGroup("行业"));//行业
		modelAndView.addObject("industryInfo1", request.getParameter("industryName")!=null ? request.getParameter("industryName") : "");//行业
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		String s = df.format(new Date());
		modelAndView.addObject("startDate", request.getParameter("beginDate"));//开始时间
		modelAndView.addObject("endDate", request.getParameter("endDate")!=null ? request.getParameter("endDate") : df.format(new Date()));//结束时间
		modelAndView.addObject("nameDate", request.getParameter("dateTimeType")!=null?request.getParameter("dateTimeType"):"");//时间类型
		
		modelAndView.addObject("creditLevel", request.getParameter("xyName") != null ? request.getParameter("xyName") : "" );//信用评分
		modelAndView.addObject("asset", request.getParameter("Asset") != null ? request.getParameter("Asset") : "" );
		//modelAndView.addObject("contractType", request.getParameter("contractType")!=null ? request.getParameter("contractType") : "");//合同类型
		
		//String repairKindGroup = "返修类别";
		//modelAndView.addObject("repairKinds", optionService.getRepository().findByGroup(repairKindGroup));
		//modelAndView.addObject("module", module);
		return modelAndView;
	}
	//获取主界面列表中的数据
	@RequestMapping(value = "Allgetpage", method = RequestMethod.GET)
	public Map<String, Object> getUserPage(HttpServletRequest request) {
		/*Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String deptkey = request.getParameter("deptkey");
		String businkey = request.getParameter("businkey");
		String xinyongkey = request.getParameter("xinyongkey");
		String zicankey = request.getParameter("zicankey");
		List<EXDEcustomerViewTotal> contracts = exdeCustomerViewTotalService.getUser(start, length,deptkey,businkey,xinyongkey,zicankey);
		long count = exdeCustomerViewTotalService.getAllUserCount(deptkey,businkey,xinyongkey,zicankey);
		map.put("data", contracts);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;*/
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> qMap = new HashMap<String, Object>();
		Map<String, Object> condition = new HashMap<String, Object>();
		Map<String, Object>numMap=new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		Account a = this.getMyAccount();
		//Module module = this.getPageModule("contractInfoView");
		//String dataFilter = module.getDataFilter();
		String dataFilter = "";
		User user = a.getUser();
		this.getQueryParams(qMap,numMap);
		condition.put("qMap", qMap);
		condition.put("numMap", numMap);
		
		String userId = a.getUser().getId();
		String Superior = a.getUser().getSaleArea().getSuperior();//权限部门
		String areaName = a.getUser().getSaleArea().getAreaName();
		if (userId == null) {
			userId = "";
		}
		if (Superior == null) {
			Superior = "";
		}
		if (areaName == null) {
			areaName = "";
		}
		/*if (dataFilter == null) {
			dataFilter = "";
		}*/
		condition.put("userId", userId);
		condition.put("superior", Superior);
		condition.put("areaName", areaName);
		condition.put("dataFilter", dataFilter);
		List<EXDEcustomerViewTotal> contracts = exdeCustomerViewTotalService.getcustomerInfos(start, length, condition, user, "createTime", "desc");
		List<EXDEcustomerViewTotal> contractsum = exdeCustomerViewTotalService.getcustomerInfos(0, Integer.MAX_VALUE, condition, user, "createTime","desc");
		long count = contractsum.size();
		map.put("data", contracts);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	@RequestMapping(value = "see", method = RequestMethod.GET)
	public ModelAndView customerSee(HttpServletRequest request) {
		ModelAndView mv = this.createLayoutView("CustomerTotal/CustomerTotalView");
		String customerId = request.getParameter("customerId");
		Customer customer = customerService.getRepository().findById(customerId);
		mv.addObject("customer", customer);
		Account a = this.getMyAccount();
		String superior = a.getUser().getSaleArea().getSuperior(); 
		List<SaleArea> saleAreas = saleAreaService.getRepository().findBySuperior(superior);
		if (saleAreas.size() > 0) {
			mv.addObject("saleAreas", saleAreas);
		}
		
		return mv;
	}
	
		//价格单数据
		@RequestMapping(value = "price", method = RequestMethod.GET)
		public Map<String, Object> getpricePage(HttpServletRequest request) {
			Map<String, Object> map = new HashMap<String, Object>();
			int start = Integer.parseInt(request.getParameter("start"));
			int length = Integer.parseInt(request.getParameter("length"));
			String key = request.getParameter("key");
			List<CustomerPriceView> contracts = exdeCustomerPriceViewService.getPriceList(start, length, key);
			long count = exdeCustomerPriceViewService.getAllPriceCount(key);
			map.put("data", contracts);
			map.put("draw", request.getParameter("draw"));
			map.put("recordsFiltered", count);
			map.put("recordsTotal", count);
			return map;
		}
	/**
	 * hql
	 * @param qMap
	 * @param numMap
	 */
		private void getQueryParams(Map<String, Object> qMap,Map<String, Object>numMap){
			String names[]={"sSuperiorArea","business","asset","creditLevel"};//部门-片区，行业，资产性质
			String dates[] = {"createTime"};
			for(String name:names){
				System.out.println(request.getParameter(name));
				String aa =  request.getParameter(name);
				if(StringUtils.hasText(request.getParameter(name))){
					String[] a = request.getParameter(name).toString().split(",");
					String b = "";
					for(int i=0;i<a.length;i++){
						b += "'" + a[i] + "',";
					}
					b = b.substring(0, b.length()-1);
					numMap.put(name, b);
				}
				
			}
			//String ab = request.getParameter("creditLevel").toString();
			//System.out.println(ab+" ");
			//信用评分
			if(StringUtils.hasText(request.getParameter("creditLevel"))){
				numMap.put("creditLevel", request.getParameter("creditLevel").toString());
			}
			if(StringUtils.hasText(request.getParameter("customerName"))){
				System.out.println(request.getParameter("customerName"));
				numMap.put("customerName", request.getParameter("customerName").toString());
			}
			for(String date:dates){
				if(null!=this.getDateQueryItem(date)){
					qMap.put(date,this.getDateQueryItem(date));
				}
			}
			
		}
}
